package com.example.musicplayer.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.example.musicplayer.MusicPlayerApplication;
import com.example.musicplayer.R;
import com.example.musicplayer.adapter.BaseFragmentPagerAdapter;
import com.example.musicplayer.commonUtils.DrawUtil;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.fragment.dialogFragment.MusicListDialogFragment;
import com.example.musicplayer.fragment.MusicPlayTab1Fragment;
import com.example.musicplayer.fragment.MusicPlayTab2Fragment;
import com.example.musicplayer.fragment.MusicPlayTab3Fragment;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicTools.MusicPlayMode;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.windowTools.SlideLayout;
import com.example.musicplayer.windowTools.WindowTools;

import java.util.ArrayList;
import java.util.List;

public class MusicPlayActivity extends BaseActivity {
    private List<TextView> mTopTabText;
    private ViewPager mViewPagerMusicPlay;
    private MusicService.MusicBinder mMusicBinder;
    private MusicPlayTab1Fragment mMusicPlayTab1Fragment;
    private MusicPlayTab2Fragment mMusicPlayTab2Fragment;
    private MusicPlayTab3Fragment mMusicPlayTab3Fragment;
    private MusicListDialogFragment mMusicListDialogFragment;
    //滑动退出activity的布局类
    private SlideLayout mSlideLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_play);
        if ((mMusicBinder = getMusicServiceBinder()) == null) {
            finish();
        }
        mSlideLayout = new SlideLayout(this, false);
        mSlideLayout.bind();
        //设置window背景图
        setWindowBackground();

        initView();
        addListener();
        Intent intent = new Intent(this, MusicService.class);
        //设置沉浸式状态栏
        WindowTools.setStatusBarTransparent(getWindow());
        setEnableMusicListener(true);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (mMusicBinder != null && hasFocus) {
            registerMusicListener(mMusicBinder);
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //重新加载音乐列表
        if (mMusicListDialogFragment.isResumed()) {
            mMusicListDialogFragment.updateWhenChangingMusic();
        }
    }

    @Override
    public void onBackPressed() {
        finishActivity();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finishActivity();
        }
        return super.onOptionsItemSelected(item);
    }

    //得到组件对象并初始化viewPager
    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar_music_play);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //添加向上操作
            actionBar.setDisplayHomeAsUpEnabled(true);
            //去除toolbar中的标题
            actionBar.setDisplayShowTitleEnabled(false);
        }

        mTopTabText = new ArrayList<TextView>();
        mTopTabText.add((TextView) findViewById(R.id.textview_music_play_tab1));
        mTopTabText.add((TextView) findViewById(R.id.textview_music_play_tab2));
        mTopTabText.add((TextView) findViewById(R.id.textview_music_play_tab3));
        mViewPagerMusicPlay = findViewById(R.id.viewpager_music_play);
        mMusicListDialogFragment = new MusicListDialogFragment();

        List<Fragment> list = new ArrayList<Fragment>();
        mMusicPlayTab1Fragment = new MusicPlayTab1Fragment();
        mMusicPlayTab2Fragment = new MusicPlayTab2Fragment();
        mMusicPlayTab3Fragment = new MusicPlayTab3Fragment();
        list.add(mMusicPlayTab1Fragment);
        list.add(mMusicPlayTab2Fragment);
        list.add(mMusicPlayTab3Fragment);
        mViewPagerMusicPlay.setAdapter(new BaseFragmentPagerAdapter(getSupportFragmentManager(), 1, list));
        updateTopTab(mTopTabText.size() > 1 ? mTopTabText.get(1) : null);
    }

    //给组件添加监听器
    private void addListener() {
        mMusicListDialogFragment.setCallBackListener(new MusicListDialogFragment.CallBackListener() {
            @Override
            public MusicService.MusicBinder getBinder() {
                return mMusicBinder;
            }

            @Override
            public void onMusicListShow() {
            }

            @Override
            public void onMusicListDismiss() {
            }
        });

        mMusicPlayTab2Fragment.setOnCallBackListener(new MusicPlayTab2Fragment.CallBackListener() {
            @Override
            public MusicService.MusicBinder getMusicBinder() {
                return mMusicBinder;
            }

            @Override
            public void setBackground(Bitmap bitmap) {
                MusicPlayActivity.this.setBackground(bitmap);
            }

            @Override
            public void showMusicListDialog() {
                if (mMusicBinder.getMusicCounts() > 0) {
                    mMusicListDialogFragment.show(getSupportFragmentManager(), "musicListDialog");
                }
            }

            @Override
            public void switchFragment(int position) {
                if (position >= 0 && position < mTopTabText.size()) {
                    updateTopTab(mTopTabText.get(position));
                }
            }
        });

        mMusicPlayTab3Fragment.setTab3CallBackListener(new MusicPlayTab3Fragment.Tab3CallBackListener() {
            @Override
            public MusicService.MusicBinder getMusicBinder() {
                return mMusicBinder;
            }

            @Override
            public void musicLyricChanged(String lyric) {
                mMusicPlayTab2Fragment.changeMusicLyric(lyric);
            }
        });

        for (int i = 0; i < mTopTabText.size(); i++) {
            final TextView view = mTopTabText.get(i);
            if (view != null)
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        updateTopTab(view);
                    }
                });
        }
        //分享功能
        View viewShare = findViewById(R.id.imageview_music_play_share);
        if (viewShare != null) {
            viewShare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    doClickShare();
                }
            });
        }

        mViewPagerMusicPlay.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position < mTopTabText.size())
                    updateTopTab(mTopTabText.get(position));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    //分享歌曲
    private void doClickShare() {
        ToastUtil.makeToast("这是分享的功能");
    }

    //更新页面顶部栏的选择状态
    private void updateTopTab(TextView view) {
        int position = mTopTabText.contains(view) ? mTopTabText.indexOf(view) : 0;
        mViewPagerMusicPlay.setCurrentItem(position);
        for (int i = 0; i < mTopTabText.size(); i++) {
            if (i == position) {
                mTopTabText.get(i).setTextColor(getResources().getColor(R.color.white));
            } else {
                mTopTabText.get(i).setTextColor(getResources().getColor(R.color.light_gray));
            }
            mSlideLayout.setEnable(position == 1 && MusicPlayerSettings.isAnimEffect());
        }
    }

    //设置背景图
    private void setWindowBackground() {
        Bitmap screenShot = MusicPlayerApplication.getInstance().getScreenShot();
        if (screenShot != null) {
            getWindow().setBackgroundDrawable(new BitmapDrawable(getResources(), screenShot));
            MusicPlayerApplication.getInstance().clearScreenShot();
        }
    }

    //结束这个activity
    private void finishActivity() {
        finish();
        setPendingTransition(R.anim.fake_anim, R.anim.music_play_activity_exit);
    }

    private void setBackground(Bitmap bitmap) {
        if (MusicPlayerSettings.isSetPlayScreenBg()) {
            bitmap = MusicPlayerSettings.getPlayScreenImageBitmap();
        }
        //获取与屏幕等比例的图片
        bitmap = DrawUtil.getMatchScreenBitmap(this, bitmap);
        //图片高斯模糊处理
        for (int i = 1; i <= 1; i++)
            bitmap = DrawUtil.blurBitmap(this, bitmap, 25);
        //获取图片的主色
        int color = DrawUtil.getMainColorOfPicture(bitmap, DrawUtil.DARK_VIBRANT);
        //加上一定的透明度
        color = Color.argb(MusicPlayerSettings.getAlphaOfPictureMainColor()
                , Color.red(color), Color.green(color), Color.blue(color));
        if (bitmap != null) {
            Canvas canvas = new Canvas(bitmap);
            //画上主色
            canvas.drawColor(color);
            //画上背景色遮罩
            canvas.drawColor(getResources().getColor(R.color.music_play_background_1));
        }
        Drawable drawable = new BitmapDrawable(getResources(), bitmap);
        //设置背景
        View backgroundView = findViewById(R.id.music_play_background);
        if (backgroundView != null)
            backgroundView.setBackground(drawable);
    }

    @Override
    public void onMusicPrepared(MusicInfo musicInfo) {
        if (mMusicPlayTab2Fragment != null && mMusicPlayTab2Fragment.getActivity() != null)
            mMusicPlayTab2Fragment.updateMusicPrepared();
        if (mMusicPlayTab3Fragment != null && mMusicPlayTab3Fragment.getActivity() != null)
            mMusicPlayTab3Fragment.updateMusicPrepared();
        if (mMusicListDialogFragment.isResumed() && mMusicListDialogFragment.getActivity() != null) {
            mMusicListDialogFragment.updateWhenChangingMusic();
        }
    }

    @Override
    public void onMusicEmpty(MusicInfo musicInfo) {
        finishActivity();
    }

    @Override
    public void onMusicFavoriteChanged(MusicInfo musicInfo, boolean result) {
        if (mMusicPlayTab2Fragment != null && mMusicPlayTab2Fragment.getActivity() != null) {
            mMusicPlayTab2Fragment.changeMusicFavorite(result);
        }
    }

    @Override
    public void onMusicPlayStateChanged(MusicInfo musicInfo, boolean isPlaying) {
        if (mMusicPlayTab2Fragment != null && mMusicPlayTab2Fragment.getActivity() != null) {
            mMusicPlayTab2Fragment.changeMusicState(isPlaying);
        }
        if (mMusicPlayTab3Fragment != null && mMusicPlayTab3Fragment.getActivity() != null) {
            mMusicPlayTab3Fragment.changeMusicState(isPlaying);
        }
    }

    @Override
    protected void onMusicPlayModeChanged(MusicInfo musicInfo, MusicPlayMode mode) {
        if (mMusicPlayTab2Fragment != null && mMusicPlayTab2Fragment.getActivity() != null) {
            mMusicPlayTab2Fragment.updateModeChanged(mode, true);
        }
    }
}